package com.cjc.sport.controller.user;

import com.cjc.sport.controller.BaseController;
//import com.cjc.sport.entity.*;
import com.cjc.sport.entity.EnumValidation;
import com.cjc.sport.entity.NumEnum;
import com.cjc.sport.entity.ReturnJson;
import com.cjc.sport.entity.Shuffling;
import com.cjc.sport.entity.SelectCourse;
import com.cjc.sport.entity.UserTemp;
import com.cjc.sport.entity.Article;
import com.cjc.sport.entity.Category;
import com.cjc.sport.entity.Course;
import com.cjc.sport.exception.CourseException;
import com.cjc.sport.exception.ServiceException;
import com.cjc.sport.service.UserService;
import com.cjc.sport.util.HttpUtil;
import com.cjc.sport.util.SportUtils;
import com.github.pagehelper.Page;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 用户界面控制层
 *
 * @Author: Bruse Queen
 * @Date: 2018/2/28
 */
@RestController
@CrossOrigin
public class UserController extends BaseController {
    /**
     * 日志配置
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(UserController.class);
    /**
     * 引入配置文件
     */
    @Autowired
    private Environment environment;
    /**
     * 装配用户服务层
     */
    @Autowired
    private UserService userService;
    /**
     * @result 统一返回对象名
     */
    private static ReturnJson result = new ReturnJson();

    /**
     * json返回
     */
    private JsonObject lastResult;

    /**
     * 获取配置文件
     */
    @Value("${getUserInfoByRSAUrl}")
    private String getUserInfoByRSAUrl;

    /**
     * 添加一个获取数据适配PC
     *
     * @param request 请求头
     * @return json数据
     */
    @RequestMapping(value = "/getUserInfoByRSAUrl", method = RequestMethod.POST)
    public String getUserInfoByRSAUrl(HttpServletRequest request) {
        try {
//            System.out.println(combStr);

            // 获取请求头中jsonObject
            JsonObject jsonObject = getJsonObject(request);
            String combStr = jsonObject.has("combStr") ?
                    jsonObject.get("combStr").getAsString() : "";

            if ("".equals(combStr)) {
                throw new Exception("获取参数为空！");
            }
            JsonObject object = new JsonObject();
            object.addProperty("combStr", combStr);
            final String json = object.toString();
            String resultTemp = SportUtils.postData(getUserInfoByRSAUrl, json, "application/json");
//            JsonParser jsonParser = new JsonParser();
//            return (JsonObject) jsonParser.parse(resultTemp);
            return resultTemp;

        } catch (Exception e) {
            LOGGER.error("UserController--getUserInfoByRSAUrl error!", e);
            result = new ReturnJson(NumEnum.FAIL.getIndex(), e.getMessage());
        }
        return "调用适配PC出错";
    }

    /**
     * 获取上线的轮播图
     *
     * @return ReturnJson 封装标准json
     */
    @RequestMapping(value = "/user/getTrueShuffling", method = RequestMethod.POST)
    public ReturnJson getTrueShuffling() {
        try {
            // 执行查询
            List<Shuffling> shufflings = userService.getTrueShuffling();
            result = new ReturnJson(NumEnum.SUCCESS.getIndex(), "查询成功！", shufflings);

        } catch (ServiceException s) {
            LOGGER.error("UserController--getTrueShuffling error!");
            result = new ReturnJson(NumEnum.FAIL.getIndex(), s.getMessage());
        } catch (Exception e) {
            LOGGER.error("UserController--getTrueShuffling error!");
            result = new ReturnJson(NumEnum.FAIL.getIndex(), e.getMessage());
        }
        return result;
    }

    /**
     * 获得所有课程分类
     *
     * @return ReturnJson 返回封装的Json对象
     */
    @RequestMapping(value = "/user/getAllCategories", method = RequestMethod.POST)
    public ReturnJson getAllCategories() {
        try {
            // 执行查询
            List<Category> categories = userService.getAllCategories();
            result = new ReturnJson(NumEnum.SUCCESS.getIndex(), "查询成功!", categories);

        } catch (ServiceException s) {
            LOGGER.error("UserController--getAllCategories error!");
            result = new ReturnJson(NumEnum.FAIL.getIndex(), s.getMessage());
        } catch (Exception e) {
            LOGGER.error("UserController--getAllCategories error!");
            result = new ReturnJson(NumEnum.FAIL.getIndex(), e.getMessage());
        }
        return result;
    }

    /**
     * 查看是否关注订阅号
     *
     * @param request 请求url
     * @return ReturnJson 封装标准json
     */
    @RequestMapping(value = "/public/isAttention", method = RequestMethod.POST)
    public ReturnJson isAttention(HttpServletRequest request) {
        try {
            // 获取请求头中jsonObject
            JsonObject jsonObject = getJsonObject(request);
            // 用户id
            String userId = jsonObject.has("userId") ? jsonObject.get("userId").getAsString() : "";
            // 订阅号id
            String mpId = environment.getProperty("mpId.parameter");
            // 调用外部接口
            HttpUtil.Request req = new HttpUtil.Request();
            req.setSpec(environment.getProperty("isAttention.url"));
            req.getData().put("mpId", mpId);
            req.getData().put("userId", userId);
            // 解析返回json
            JsonObject json = new JsonParser().parse(HttpUtil.asString(req)).getAsJsonObject();
            JsonObject jsonData = json.get("data").getAsJsonObject();
            // 判断接口调用情况
            int i = json.has("resultCode") ? json.get("resultCode").getAsInt() : 0;
            if (i != 1) {
                throw new ServiceException("接口调用失败!");
            }

            int j = jsonData.has("status") ? jsonData.get("status").getAsInt() : EnumValidation.TWO.getNum();
            if (j == EnumValidation.TWO.getNum()) {
                throw new ServiceException("接口调用成功，但无状态码！");
            }
            result = new ReturnJson(NumEnum.SUCCESS.getIndex(), "查看订阅状态成功!", j);

        } catch (ServiceException s) {
            LOGGER.error("UserController--isAttention error!");
            result = new ReturnJson(NumEnum.FAIL.getIndex(), s.getMessage());
        } catch (Exception e) {
            LOGGER.error("UserController--isAttention error!");
            result = new ReturnJson(NumEnum.FAIL.getIndex(), e.getMessage());
        }
        return result;
    }

    /**
     * 关注订阅号
     *
     * @param request 请求url
     * @return ReturnJson 封装标准json
     */
    @RequestMapping(value = "/public/addAttention", method = RequestMethod.POST)
    public ReturnJson addAttention(HttpServletRequest request) {
        try {
            // 获取请求头中jsonObject
            JsonObject jsonObject = getJsonObject(request);
            // 用户id
            String userId = jsonObject.has("userId") ? jsonObject.get("userId").getAsString() : "";
            // 订阅号id
            String mpId = environment.getProperty("mpId.parameter");
            // 调用外部接口
            HttpUtil.Request req = new HttpUtil.Request();
            req.setSpec(environment.getProperty("addAttention.url"));
            req.getData().put("mpId", mpId);
            req.getData().put("userId", userId);

            // 解析返回json
            JsonObject json = new JsonParser().parse(HttpUtil.asString(req)).getAsJsonObject();
            JsonObject jsonData = json.get("data").getAsJsonObject();
            // 判断接口调用请
            int i = json.has("resultCode") ? json.get("resultCode").getAsInt() : 0;
            if (i != 1) {
                throw new ServiceException("接口调用失败!");
            }

            int j = jsonData.has("sub") ? jsonData.get("sub").getAsInt() : EnumValidation.TWO.getNum();
            if (j == EnumValidation.TWO.getNum()) {
                throw new ServiceException("接口调用成功，但无状态码！");
            }
            result = new ReturnJson(NumEnum.SUCCESS.getIndex(), "订阅成功!", j);

        } catch (ServiceException s) {
            LOGGER.error("UserController--addAttention error!");
            result = new ReturnJson(NumEnum.FAIL.getIndex(), s.getMessage());
        } catch (Exception e) {
            LOGGER.error("UserController--addAttention error!");
            result = new ReturnJson(NumEnum.FAIL.getIndex(), e.getMessage());
        }
        return result;
    }

    /**
     * 取消关注
     *
     * @param request 请求url
     * @return ReturnJson 封装标准json
     */
    @RequestMapping(value = "/public/deleteAttention", method = RequestMethod.POST)
    public ReturnJson deleteAttention(HttpServletRequest request) {
        try {
            // 获取请求头中jsonObject
            JsonObject jsonObject = getJsonObject(request);
            // 用户id
            String userId = jsonObject.has("userId") ? jsonObject.get("userId").getAsString() : "";
            // 订阅号id
            String mpId = environment.getProperty("mpId.parameter");
            // 调用外部接口
            HttpUtil.Request req = new HttpUtil.Request();
            req.setSpec(environment.getProperty("deleteAttention.url"));
            req.getData().put("mpId", mpId);
            req.getData().put("userId", userId);

            // 解析返回json
            JsonObject json = new JsonParser().parse(HttpUtil.asString(req)).getAsJsonObject();
            JsonObject jsonData = json.get("data").getAsJsonObject();
            // 判断接口调用情况
            int i = json.has("resultCode") ? json.get("resultCode").getAsInt() : 0;
            if (i != 1) {
                throw new ServiceException("接口调用失败!");
            }

            int j = jsonData.has("sub") ? jsonData.get("sub").getAsInt() : EnumValidation.TWO.getNum();
            if (j == EnumValidation.TWO.getNum()) {
                throw new ServiceException("接口调用成功，但无状态码！");
            }
            result = new ReturnJson(NumEnum.SUCCESS.getIndex(), "取消订阅成功!", j);

        } catch (ServiceException s) {
            LOGGER.error("UserController--deleteAttention error!");
            result = new ReturnJson(NumEnum.FAIL.getIndex(), s.getMessage());
        } catch (Exception e) {
            LOGGER.error("UserController--deleteAttention error!");
            result = new ReturnJson(NumEnum.FAIL.getIndex(), e.getMessage());
        }
        return result;
    }


    /**
     * 获取文章
     *
     * @param request 请求url
     * @return ReturnJson 封装标准json
     */
    @RequestMapping(value = "/public/getMpHistory", method = RequestMethod.POST)
    public ReturnJson getMpHistory(HttpServletRequest request) {
        try {
            // 获取请求头中jsonObject
            JsonObject jsonObject = getJsonObject(request);
            // 页数
            int pageNo = jsonObject.has("pageNum")
                    ? jsonObject.get("pageNum").getAsInt() : 0;
            // 每页条数
            int pageSize = jsonObject.has("pageSize")
                    ? jsonObject.get("pageSize").getAsInt() : EnumValidation.TWO.getNum();
            // 页数减一
            if (pageNo != 0) {
                pageNo--;
            }
            // 获取参数
//            String mpId = jsonObject.has("mpId")
////                    ? jsonObject.get("mpId").getAsString() : "0";
//            String client = environment.getProperty("client.parameter");
            String mpId = environment.getProperty("mpId.parameter");
            String type = environment.getProperty("type.parameter");

            // 调用外部接口
            HttpUtil.Request req = new HttpUtil.Request();
            req.setSpec(environment.getProperty("getMpHistory.url"));
            // 订阅号id
            req.getData().put("mpId", mpId);
//            req.getData().put("client", client);
            req.getData().put("type", type);
            req.getData().put("pageNo", pageNo);
            req.getData().put("pageSize", pageSize);

            // 解析返回json
            JsonObject json = new JsonParser().parse(HttpUtil.asString(req)).getAsJsonObject();
            // 获取总条数
            int total = json.has("total") ? json.get("total").getAsInt() : 0;
            // 判断接口调用情况
            int i = json.has("resultCode") ? json.get("resultCode").getAsInt() : 0;
            if (i != 1) {
                throw new ServiceException("接口调用失败!");
            }
            // 获取数据
            JsonArray jsonData = json.get("data").getAsJsonArray();
            // 解析为封装对象
            List<Article> articles = SportUtils.getArticle(jsonData);
            result = new ReturnJson(NumEnum.SUCCESS.getIndex(), "接口调用成功！", articles, total);

        } catch (ServiceException s) {
            LOGGER.error("UserController--getMpHistory error!");
            result = new ReturnJson(NumEnum.FAIL.getIndex(), s.getMessage());
        } catch (Exception e) {
            LOGGER.error("UserController--getMpHistory error!");
            result = new ReturnJson(NumEnum.FAIL.getIndex(), e.getMessage());
        }
        return result;
    }

    /**
     * 新增uset_temp表
     *
     * @param request 请求对象
     * @return ReturnJson 封装标准json
     */
    @RequestMapping(value = "/user/addUserTemp", method = RequestMethod.POST)
    public ReturnJson addUserTemp(HttpServletRequest request) {
        try {
            // 获取请求头中jsonObject
            JsonObject jsonObject = getJsonObject(request);

            // 用户ID
            String userId = jsonObject.has("USER_ID")
                    ? jsonObject.get("USER_ID").getAsString() : "0";
            // 用户头像
            String icon = jsonObject.has("ICON")
                    ? jsonObject.get("ICON").getAsString() : "0";
            // 用户学号
            String xh = jsonObject.has("XH")
                    ? jsonObject.get("XH").getAsString() : "0";
            // 用户名字
            String name = jsonObject.has("XM")
                    ? jsonObject.get("XM").getAsString() : "0";
            // 用户性别
            String xbm = jsonObject.has("XBM")
                    ? jsonObject.get("XBM").getAsString() : "0";


            // 用户证件号码
            String cardId = jsonObject.has("SFZJH")
                    ? jsonObject.get("SFZJH").getAsString() : "0";
            // 用户院系
            String departments = jsonObject.has("DEPARTMENTS")
                    ? jsonObject.get("DEPARTMENTS").getAsString() : "0";

            // 用户专业
            String professional = jsonObject.has("PROFESSIONAL")
                    ? jsonObject.get("PROFESSIONAL").getAsString() : "0";
            // 用户年级
            String grade = jsonObject.has("NJH")
                    ? jsonObject.get("NJH").getAsString() : "0";
            // 用户班级
            String classGrade = jsonObject.has("CLASS_GRADE")
                    ? jsonObject.get("CLASS_GRADE").getAsString() : "0";
            // 用户联系电话
            String tel = jsonObject.has("TEL")
                    ? jsonObject.get("TEL").getAsString() : "0";


            // 专职导师工号
            String mentoGh = jsonObject.has("MENTO_GH")
                    ? jsonObject.get("MENTO_GH").getAsString() : "0";
            // 用户专职导师姓名
            String mentorName = jsonObject.has("MENTOR_NAM")
                    ? jsonObject.get("MENTOR_NAM").getAsString() : "0";
            // 用户专职导师电话
            String mentorTel = jsonObject.has("MENTOR_TEL")
                    ? jsonObject.get("MENTOR_TEL").getAsString() : "0";

            // im编号
            String imAccount = jsonObject.has("IM_ACCOUNT")
                    ? jsonObject.get("IM_ACCOUNT").getAsString() : "0";
            // 封装对象
            UserTemp userTemp = new UserTemp(userId, icon, xh, name, xbm, cardId, departments, professional,
                    grade, classGrade, tel,
                    mentoGh, mentorName, mentorTel, imAccount);
            // 执行新增
            userService.addUserTemp(userTemp);
            result = new ReturnJson(NumEnum.SUCCESS.getIndex(), "新增成功！");

        } catch (ServiceException s) {
            LOGGER.error("UserController--addUserTemp error!");
            result = new ReturnJson(NumEnum.FAIL.getIndex(), s.getMessage());
        } catch (Exception e) {
            LOGGER.error("UserController--addUserTemp error!");
            result = new ReturnJson(NumEnum.FAIL.getIndex(), e.getMessage());
        }
        return result;
    }

    /**
     * 依据条件查询课程表
     *
     * @param selectCourse 查询相关参数对象
     * @return ReturnJson 封装标准json
     */
    @RequestMapping(value = "/user/selectByCondition", method = RequestMethod.POST)
    public ReturnJson selectByCondition(@RequestBody SelectCourse selectCourse) {
        try {
            // 校验字段
            if (selectCourse.getCourseName().equals("")) {
                selectCourse.setCourseName(null);
            }
            if (selectCourse.getCategoryName().equals("")) {
                selectCourse.setCategoryName(null);
            }
            if (selectCourse.getCourseTag().equals("")) {
                selectCourse.setCourseTag(null);
            }
            // 执行查询
            Page<Course> coursePageInfo = userService.selectByCondition(selectCourse.getCourseName(),
                    selectCourse.getCategoryName(), selectCourse.getCourseTag(), selectCourse.getPageNum(),
                    selectCourse.getPageSize());
            result = new ReturnJson(NumEnum.SUCCESS.getIndex(), "查询成功！", coursePageInfo, coursePageInfo.getTotal());

        } catch (CourseException c) {
            LOGGER.error("UserController--selectByCondition error!");
            result = new ReturnJson(NumEnum.FAIL.getIndex(), c.getMessage());
        } catch (Exception e) {
            LOGGER.error("CategoryController--addCategory error!");
            result = new ReturnJson(NumEnum.FAIL.getIndex(), e.getMessage());
        }
        return result;
    }


}
